package cn.whit.blog.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.whit.blog.domain.EmailType;
import cn.whit.blog.domain.User;
import cn.whit.blog.service.UserService;
import cn.whit.blog.util.BeanFactory;
import cn.whit.blog.util.DynamicQuery;
import cn.whit.blog.util.MD5Utils;
import cn.whit.blog.util.PageModel;
import cn.whit.blog.util.Parameter;
import cn.whit.blog.util.UUIDUtils;

public class UserServlet extends BaseServlet{
	
	private static final long serialVersionUID = 1807233726002050760L;
	
	UserService userService = (UserService)BeanFactory.createObject("userService");
	
	//批量删除数据
	public String delete(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		System.out.println(request.getParameter("ids"));
		String ids = request.getParameter("ids");
		
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(ids != null) {
			String[] split = ids.split(",");
			System.out.println(split.length);
			for(String s: split) {
				System.out.println(s);
				userService.deleteById(s);
			}
			writer.write("删除成功".toString());
			return null;
		}
		writer.write("删除失败，请联系管理员".toString());
		return null;
	}
	
	
	//去用户登录页面
	public String tologin (HttpServletRequest request, HttpServletResponse response) throws Exception {
		return "/view/user/login.jsp";
	}
	
	//用户登录
	public String login (HttpServletRequest request, HttpServletResponse response) throws Exception {
		//登录名
		String userName = request.getParameter("userName");
		//密码
		String password = request.getParameter("password");
		
		//验证登录名和密码
		List<User> users =  userService.findByUserNameAndPassword(userName,MD5Utils.md5(password));
		if(users != null && users.size() == 1 ) {
			if(users.get(0).getActivecode() != null && users.get(0).getActivecode().length() > 0) {
				//新用户注册，还未邮箱确认
				//登录名或者邮箱重复
				request.setAttribute("message", "请先通过注册的邮箱验证再登录");
				return "/view/user/login.jsp";
			}
			if(users.get(0).getStatus() != 1) {
				//登录账号状态异常
				request.setAttribute("message", "登录账号状态异常,请联系管理员");
				return "/view/user/login.jsp";
			}
			
			//如果该用户已经登录（在线）， 1 提示该账户已经登录  2 则踢出已登录用户，清空session  采用2 的方式解决
			HashMap<String,HttpSession> userIdAndSessionMap = null;
			if(request.getServletContext().getAttribute("userIdAndSessionMap") != null) {
				userIdAndSessionMap = (HashMap<String,HttpSession>) request.getServletContext().getAttribute("userIdAndSessionMap");
			}else {
				//初始化所有在线用户id和session的map
				userIdAndSessionMap = new HashMap<String,HttpSession>();
				request.getServletContext().setAttribute("userIdAndSessionMap", userIdAndSessionMap);
			}
			
			if(userIdAndSessionMap.containsKey(users.get(0).getId())) {
				//该用户已经登录在线了,  采用2 的方式解决 踢出已登录用户，并清空其session
				System.out.println("踢出之前该账户的登录数据.....");
				//request.setAttribute("message", "登录账号正在登录中,请联系管理员");   //采用1的方式解决
				userIdAndSessionMap.get(users.get(0).getId()).invalidate();
				//将当前登录账号信息加入
				userIdAndSessionMap.put(users.get(0).getId(), request.getSession());
				request.getServletContext().setAttribute("userIdAndSessionMap", userIdAndSessionMap);
			}else {
				//放入用户id和session的map
				userIdAndSessionMap.put(users.get(0).getId(), request.getSession());
				request.getServletContext().setAttribute("userIdAndSessionMap", userIdAndSessionMap);
			}
			 
			
			//如果是管理员，跳转到管理页面,groupid=0
			if("0".equals(users.get(0).getGroupid())) {
				request.getSession().setAttribute("loginUser", users.get(0)); 
				response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
				return null;
			}
			
			//普通用户登录成功，重定向到博客首页 
			request.getSession().setAttribute("loginUser", users.get(0));
			response.sendRedirect("TblogServlet?method=index");
			return null;
		}else {
			//登录名或者邮箱错误
			request.setAttribute("userName", userName);
			request.setAttribute("message", "登录名或密码错误");
			return "/view/user/login.jsp";
		}
	}
	
	//注册新用户
	public String reguser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//登录名
		String userName = request.getParameter("userName");
		//邮箱
		String email = request.getParameter("email");
		//密码
		String password = request.getParameter("password");
		//验证登录名或邮箱是否重复
		List<User> users =  userService.findByUserNameOrEmail(userName,email);
		if(users != null && users.size() > 0) {
			//登录名或者邮箱重复
			request.setAttribute("userName", userName);
			request.setAttribute("email", email);
			request.setAttribute("message", "注册名或登录邮箱重复");
			return "/view/user/register.jsp";
			
		}else {
			//保存用户  注册成功，重定向到登录页面
			User newUser = new User();
			newUser.setName(userName);
			newUser.setEmail(email);
			newUser.setPassword(MD5Utils.md5(password));
			newUser.setRegDateTime(new Date());
			newUser.setStatus(0);
			
			 
			newUser.setActivecode(UUIDUtils.getId());
			
			userService.save(newUser);
			
			request.setAttribute("message", "注册成功，请去邮箱登录验证后再登录");
			response.sendRedirect("view/user/login.jsp");
			return null;
		}
	}
	
	//邮箱激活新用户 
	public String active(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//服务端获取到激活码,和数据库中已经存在的激活码对比,如果存在,激活成功,更改用户激活状态1,转发到登录页面,提示:激活成功,请登录.
		String activecode = request.getParameter("activecode");
		//调用业务层功能:根据激活码查询用户 select * from user where activecode=?
		List<User> users = userService.findByActivecode (activecode);
		//如果用户不为空,激活码正确的,可以激活
		if(null!= users && users.size() == 1){
			User user = users.get(0);  
			//这里设置activecode为空字符串，表示清空这个值，也就是邮箱验证码就验证一次
			user.setActivecode(null);
			user.setStatus(1);
			userService.update(user);
		}
		//转发到登录页面,提示:激活成功,请登录
		request.setAttribute("msg", "用户激活成功,请登录");
		response.sendRedirect(request.getContextPath()+"/view/user/login.jsp");
		return null;
	}
	
	//通过邮箱密码找回
	public String backpassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String email = request.getParameter("email");
		List<User> users = userService.findByEmail(email);
		// 
		if(null!= users && users.size() == 1){
			User user = users.get(0);  
			if(user.getStatus() == 1) {
				//用户状态正常的，重置密码为随机，发送到用户邮箱
				String newpass = UUIDUtils.getCode();
				user.setPassword(MD5Utils.md5(newpass));
				user.setActivecode(null);
				userService.update(user);
				userService.sendEmail(user,EmailType.backPassword,newpass);
				request.setAttribute("message", "密码已发到用户邮箱,请查看登录");
			}else {
				request.setAttribute("message", "用户状态异常，请联系管理员");
				return "/view/user/backpassword.jsp";
			}
		}else {
			request.setAttribute("message", "注册邮箱不存在，请联系管理员");
			return "/view/user/backpassword.jsp";
		}
		response.sendRedirect(request.getContextPath()+"/view/user/login.jsp");
		return null;
	}
	
	public String userList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//num是传入的当前页
		String num = request.getParameter("num");
		String nameSelected = request.getParameter("nameSelected");
		System.out.println(nameSelected);
		if(num == null) {
			num = "1";
		}
		//获取当前页
		int curNum = Integer.parseInt(num);
		int pageSize  = 5 ;
		DynamicQuery query = new DynamicQuery(); 
		if(nameSelected != null && !("".equals(nameSelected))) {
			//查询参数如果要验证数据类型等，在这里执行
			query.addParameter(new Parameter("name", "like", "%"+nameSelected+"%"));
			request.setAttribute("name", nameSelected);
		}
//	    query.addParameter(new Parameter("name", "like", "whit"));  ;
		PageModel pm = userService.findByPageAndQuery(curNum, pageSize, query);
		request.setAttribute("page", pm);
		return "/jsp/user/userList.jsp";
	}
	
	//用户密码找回 
	public String updatepassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String oldpassword = request.getParameter("oldpassword");
		String password = request.getParameter("password");
		String name  = request.getParameter("name");
		//检查旧密码
		List<User> users = userService.findByUserNameAndPassword(MD5Utils.md5(name), oldpassword);
		if(null != users && users.size() == 1) {
			//重置该用户密码
			User user = users.get(0);
			user.setPassword(MD5Utils.md5(name));
			userService.update(user);
			request.getSession().invalidate();
			response.sendRedirect(request.getContextPath()+"/view/user/login.jsp");
			return null;
		}
		
		request.setAttribute("message", "旧密码错误");
		return "/view/user/modifypassword.jsp";
	}
	
	//注销
	public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//用户退出,清空用户session
		request.getSession().invalidate();
		
		//下面的是清除自动登录的todo
//		Cookie ck=CookUtils.getCookieByName("autoLogin", request.getCookies());
//		if(null!=ck){
//			ck.setMaxAge(0);
//			ck.setPath("/store");
//			response.addCookie(ck);
//		}
		
		response.sendRedirect(request.getContextPath()+"/view/user/login.jsp");
		return null;
	}
	
	//hello
	public String hello(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
		//请求转发
		return "/jsp/hello.jsp";
	}

}
